package com.tyl.xtk.config;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.tyl.xtk.beans.po.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

// java example
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        String username = "unknown";
        if (StpUtil.isLogin()) {
            User user = StpUtil.getSession().getModel("user", User.class);
            if (user != null) {
                username = user.getUsername();
            }
        }


        this.strictInsertFill(metaObject, "createBy", String.class, username);
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String username = "unknown";
        if (StpUtil.isLogin()) {
            User user = StpUtil.getSession().getModel("user", User.class);
            if (user != null) {
                username = user.getUsername();
            }
        }

        this.strictUpdateFill(metaObject, "updateBy", String.class, username);
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}